package com.hjl.sr.security;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;

import com.hjl.sr.remoting.ServletEncryptContext;
import com.hjl.sr.security.token.ServerTokenManager;
import com.hjl.sr.security.token.TokenManager;
import com.hjl.sr.util.TokenStoreServiceHolder;

/**
 * @author pister
 * 2012-12-17 下午08:36:18
 */
public class SecurityHttpInvokerServiceExporter extends HttpInvokerServiceExporter {

	private Encrypter encrypter;
	
	public SecurityHttpInvokerServiceExporter(String encryptKey, TokenManager tokenManager) {
		BlowFishEncrypter blowFishEncrypter = new BlowFishEncrypter(encryptKey);
		encrypter = new PrefixTokenEncrypter(blowFishEncrypter, tokenManager);
	}
	
	public SecurityHttpInvokerServiceExporter(String encryptKey) {
		this(encryptKey, new ServerTokenManager(TokenStoreServiceHolder.getTokenStoreService()));
	}

	@Override
	protected InputStream decorateInputStream(HttpServletRequest request, InputStream is) throws IOException {
		return getEncrypter().decryptInputStream(is, new ServletEncryptContext(request, null));
	}

	@Override
	protected OutputStream decorateOutputStream(HttpServletRequest request, HttpServletResponse response, OutputStream os) throws IOException {
		return getEncrypter().encryptOutputStream(os, new ServletEncryptContext(request, response));
	}

	protected Encrypter getEncrypter() {
		return encrypter;
	}
	
}
